//
//  EFLocationManager.m
//  EnjogFood
//
//  Created by 王芳 on 17/5/9.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFLocationManager.h"
#import "EFCoorTrans.h"
#import "EFUserLocationItem.h"

static NSString * const kIsLocPermissionAlertShowedKey = @"kIsLocPermissionAlertShowedKey";
@interface EFLocationManager ()<BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
@property (nonatomic, strong) BMKLocationService   *locationService;
@property (nonatomic, strong) CLLocationManager    *locationManager;
@property (nonatomic, assign) BOOL isLocPermissionAlertShowed;
@property (strong, nonatomic) BMKGeoCodeSearch *search;
@property (assign, nonatomic) NSInteger totalTimes;

@end

@implementation EFLocationManager

- (id)init{
    self = [super init];
    if (self) {
        self.locationService = [[BMKLocationService alloc] init];
        self.pinLocation = [[EFUserLocationItem alloc] init];
        
        _isLocPermissionAlertShowed = [[NSUserDefaults standardUserDefaults] boolForKey:kIsLocPermissionAlertShowedKey];
        _totalTimes = 0;
    }
    return self;
}

- (BOOL)locationServicesEnabled {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    BOOL statusEnabled = IOS8_OR_LATER ? (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) : status == kCLAuthorizationStatusAuthorized;
    return [CLLocationManager locationServicesEnabled] && statusEnabled ;
}

- (void)checkLocationPermission:(void(^)())enableBlock disableBlock:(void(^)())disableBlock
{
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            if (enableBlock) {
                enableBlock();
            }
        }
            break;
        case kCLAuthorizationStatusNotDetermined:
        {
            if (!self.isLocPermissionAlertShowed) {
                [self.locationManager requestAlwaysAuthorization];
                self.isLocPermissionAlertShowed = YES;
                [[NSUserDefaults standardUserDefaults] setBool:self.isLocPermissionAlertShowed forKey:kIsLocPermissionAlertShowedKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
                if (disableBlock) {
                    disableBlock();
                }
            }
            else {
                RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{
                    if (disableBlock) {
                        disableBlock();
                    }
                }];
                RIButtonItem *settingItem = [RIButtonItem itemWithLabel:@"去设置" action:^{
                    if (IOS7_OR_EARLYER) {
                        NSURL *settingUrl= [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
                        if (settingUrl && [[UIApplication sharedApplication] canOpenURL:settingUrl]) {
                            [[UIApplication sharedApplication] openURL:settingUrl];
                        }
                    }
                    else if (IOS10_OR_LATER) {
                        NSURL* settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        if (settingUrl && [[UIApplication sharedApplication] canOpenURL:settingUrl]) {
                            [[UIApplication sharedApplication] openURL:settingUrl options:@{} completionHandler:nil];
                        }
                    }
                    else {
                        NSURL* settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        if (settingUrl && [[UIApplication sharedApplication] canOpenURL:settingUrl]) {
                            [[UIApplication sharedApplication] openURL:settingUrl];
                        }
                    }
                }];
                
                //                [EDJAlertViewManager alertWithTitle:@"后台定位被您禁止了" msg:@"我们需要通过您的地理位置信息获取您的周边数据，为了正常使用，请您在设置中打开定位权限"
                //                                   cancelButtonItem:cancelItem
                //                                   otherButtonItems:@[settingItem]];//EDJCustomAlertTypeLocation
                
                //                EDJCustomAlertView *alertView = [[EDJCustomAlertView alloc] initWithTitle:@"后台定位被您禁止了" message:@"我们需要通过您的地理位置信息获取您的周边数据，为了正常使用，请您在设置中打开定位权限" cancelButtonItem:cancelItem otherButtonItems:@[settingItem]];
                
            }
        }
            break;
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
        {
            RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{
                if (disableBlock) {
                    disableBlock();
                }
            }];
            RIButtonItem *settingItem = [RIButtonItem itemWithLabel:@"去设置" action:^{
                NSURL* settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if (settingUrl && [[UIApplication sharedApplication] canOpenURL:settingUrl]) {
                    if (IOS10_OR_LATER) {
                        [[UIApplication sharedApplication] openURL:settingUrl options:@{} completionHandler:nil];
                    }
                    else {
                        [[UIApplication sharedApplication] openURL:settingUrl];
                    }
                }
            }];
            
            //            [EDJAlertViewManager alertWithTitle:@"后台定位被您禁止了" msg:@"我们需要通过您的地理位置信息获取您的周边数据，为了正常使用，请您在设置中打开定位权限"
            //                               cancelButtonItem:cancelItem
            //                               otherButtonItems:@[settingItem]];
            //            EDJCustomAlertView *alertView = [[EDJCustomAlertView alloc] initWithTitle:@"后台定位被您禁止了" message:@"我们需要通过您的地理位置信息获取您的周边数据，为了正常使用，请您在设置中打开定位权限" cancelButtonItem:cancelItem otherButtonItems:@[settingItem]];
            //            alertView.alertType = EDJCustomAlertTypeLocation;
            //            [alertView show:YES];
            
        }
            break;
    }
}

- (void)startLocation{
    self.locationService.delegate = self;
    [self.locationService startUserLocationService];
    
}

- (void)stopLocation{
    [self.locationService stopUserLocationService];
    self.locationService.delegate = nil;
}

- (CLLocationManager *)locationManager {
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //至少移动distanceFilter再通知委托处理更新
        _locationManager.distanceFilter = 500.f;
        _locationManager.delegate = self;
    }
    
    return _locationManager;
}

#pragma mark BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f,title %@,subtitle %@",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude,userLocation.title,userLocation.subtitle);
    [self getDetailAdddress:userLocation.location];
}

- (void)didFailToLocateUserWithError:(NSError *)error{
    self.totalTimes ++;
    if (self.totalTimes >= 5) {
        [self stopLocation];
    }
}

/// 街道号码
//@property (nonatomic, strong) NSString* streetNumber;
/// 街道名称
//@property (nonatomic, strong) NSString* streetName;
/// 区县名称
//@property (nonatomic, strong) NSString* district;
/// 城市名称
//@property (nonatomic, strong) NSString* city;
/// 省份名称
//@property (nonatomic, strong) NSString* province;
#pragma BMKGeoCodeSearchDelegate
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == 0) {
        if (result != nil && result.addressDetail != nil && result.addressDetail.streetName.length > 0) {
            if (self.locationDelegate != nil && [self.locationDelegate respondsToSelector:@selector(getCurrentLocationName:location:)]) {
                //全局定位位置赋值
                APP_CONTEXT.locationManager.pinLocation.userCoordinate = result.location;
                APP_CONTEXT.locationManager.pinLocation.address = result.address;
                APP_CONTEXT.locationManager.pinLocation.detailAddress = [NSString stringWithFormat:@"%@%@",result.addressDetail.streetName,result.addressDetail.streetNumber];
                
                [self.locationDelegate getCurrentLocationName:[NSString stringWithFormat:@"%@%@",result.addressDetail.streetName,result.addressDetail.streetNumber] location:result.location];
//                [self stopLocation];
            }
        }
        //  NSLog(@"传入二维码解析  %@ --- %@ --- %@",result.address,result.addressDetail.streetName,result.addressDetail.streetNumber);
        
    }
    
}

- (void)getDetailAdddress:(CLLocation *)location{
    self.search = [[BMKGeoCodeSearch alloc] init];
    self.search.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
    option.reverseGeoPoint = location.coordinate;
    BOOL flag = [self.search reverseGeoCode:option];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
    
    // CLLocationCoordinate2D coordinate;
    //convert wgs84 to bd09 location
    //  coordinate = [EFCoorTrans transBD09FromWGS84Coordinate:location.coordinate];
    // CLLocation *l = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    //  [geo reverseGeocodeLocation:l completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    //      CLPlacemark *mark =  [placemarks objectAtIndex:0];
    //      if (mark.subLocality != nil) {
    //        NSString *name = mark.name;
    //         NSString *cityName = mark.locality;
    //         NSString *areaName = mark.subLocality;
    //         NSString *streetName = mark.thoroughfare;
    //         NSString *ad = mark.administrativeArea;
    //         NSString *adSub = mark.subAdministrativeArea;
    //          NSLog(@"%@-%@-%@-%@-%@-%@",name,cityName,areaName,streetName,ad,adSub);
    ///     }
    //  }];
}


@end
